﻿using Microsoft.Win32;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SQLite;

namespace Yinyueku {
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {
        SQLiteConnection? sqliteConn;
        SQLiteCommand? sqliteCmd;

        public MainWindow() {
            InitializeComponent();
            InitializeDatabase();
        }

        ~MainWindow() {
            CloseDatabase();
        }

        private void InitializeDatabase() {
            // 初始化SQLite3
            try {
                sqliteConn = new SQLiteConnection("Data Source=yinyueku.db;Version=3;");
                sqliteConn.Open();
                sqliteCmd = sqliteConn.CreateCommand();
                // 创建MusicFiles表
                sqliteCmd.CommandText = "CREATE TABLE IF NOT EXISTS MusicFiles (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, FileName TEXT NOT NULL);";
                sqliteCmd.ExecuteNonQuery();
            } catch {

            }
        }

        private void CloseDatabase() {
            sqliteConn?.Close();
        }

        private string GetSafeFileName(string file) {
            int i = file.LastIndexOf('\\');
            if (i == -1) {
                return file;
            }
            return file[++i..];
        }


        readonly string[] MUSIC_POSTFIX = ["mp3", "wav", "ape", "flac"];

        private int ImportFiles(string folder_name) {
            int count = 0;
            foreach (var file in System.IO.Directory.GetFiles(folder_name)) {
                //将文件名添加到列表中
                int i = file.LastIndexOf('.') + 1;
                if (i < file.Length) {
                    var ext = file[i..].ToLower();
                    if (System.Array.IndexOf(MUSIC_POSTFIX, ext) >= 0) {
                        lbMusic.Items.Add(file);
                        if (sqliteCmd != null) {
                            sqliteCmd.CommandText = $"INSERT INTO MusicFiles (Name, FileName) VALUES ('{GetSafeFileName(file)}', '{file}');";
                            sqliteCmd.ExecuteNonQuery();
                        }
                        count++;
                    }
                }
            }
            return count;
        }

        private int ImportFolders(string folder_name) {
            int count = ImportFiles(folder_name);
            foreach (var dir in System.IO.Directory.GetDirectories(folder_name)) {
                count += ImportFolders(dir);
            }
            return count;
        }

        /// <summary>
        /// 导入目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnImportDir_Click(object sender, RoutedEventArgs e) {
            //打开目录选择对话框
            var folderDialog = new OpenFolderDialog{
                Title = "选择文件夹",
                Multiselect = false
            };

            // 显示对话框并获取用户的选择
            if (folderDialog.ShowDialog() == true) {
                var folderName = folderDialog.FolderName;
                //遍历目录下所有文件
                int count = ImportFolders(folderName);
                if (count > 0) {
                    lbImportDirs.Items.Add(folderName);
                    MessageBox.Show($"成功导入{count}首歌曲");
                }
            }
        }
    }
}